//
//  Person.m
//  Runtime
//
//  Created by 周成龙 on 16/6/19.
//  Copyright © 2016年 none. All rights reserved.
//

#import "Person.h"

#import <objc/runtime.h>

#define  kFilePath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"user01.data"]
@implementation Person

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    unsigned int count = 0;
    Ivar *ivars = class_copyIvarList([self class], &count);
    
    for (int i = 0; i < count; i ++) {
        // 取值
        Ivar ivar = ivars[i];
        
        // 取出名称
        const char *name = ivar_getName(ivar);

        // 转成 NSString
        NSString *key = [NSString stringWithUTF8String:name];
        // 取出 key -> 编码
        [aCoder encodeObject:[self valueForKey:key] forKey:key];
    }
    
    free(ivars);
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self == [super init]) {
        
        unsigned int count = 0;
        
        Ivar *ivars = class_copyIvarList([self class], &count);
        for (int i = 0; i < count; i ++) {
            // 取值
            Ivar ivar = ivars[i];
            // 取出名称
            const char *name = ivar_getName(ivar);
            // 转成 NSString
            NSString *key = [NSString stringWithUTF8String:name];
            // 取出 key -> 解码
            id value = [aDecoder decodeObjectForKey:key];
            [self setValue:value forKeyPath:key];
        }
        free(ivars);
    }
    return self;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
    
}

- (void)save
{
    [NSKeyedArchiver archiveRootObject:self toFile:kFilePath];
}

+ (Person *)queryModel
{
    Person *model = [NSKeyedUnarchiver unarchiveObjectWithFile:kFilePath];
    return model;
}

+ (void)deleteUserInfoFile
{
    NSFileManager *fileManeger = [NSFileManager defaultManager];
    BOOL isEx = [fileManeger fileExistsAtPath:kFilePath];
    
    if (isEx) {
        NSLog(@"文件存在");
        BOOL isFinish = [fileManeger removeItemAtPath:kFilePath error:nil];
        
        if (isFinish) {
            NSLog(@"删除成功");
        }else {
            NSLog(@"删除失败");
        }
    }else {
        NSLog(@"文件不存在");
    }
}



@end
